/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package FuenteDeDatos;


import java.awt.Color;
import java.awt.Component;
import java.util.Observable;
import javax.swing.JTable;
import java.sql.*;
import java.util.Observer;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;


public class DataTable  extends JTable implements Observer{

DefaultTableCellRenderer forma = new DefaultTableCellRenderer() ;


    private Color color=new Color(0xEEEEF9);
    private DataSource data=null;

    public DataTable ()
    {

    }



     public void conectar(){

         this.getData().addObserver(this);


     }



     public void update(Observable o, Object o1) {
         DefaultTableModel modelo = new DefaultTableModel();
        try{

          ResultSetMetaData rsMetaData = data.rs.getMetaData();
          //obtiene numero de columnas
          int ncol = rsMetaData.getColumnCount();

          for ( int i = 1; i < ncol + 1; i++ )
          {
               modelo.addColumn( rsMetaData.getColumnLabel(i));
               // modelo.addColumn(rsMetaData.getColumnName(i));

          }

  Object[] fila = new Object[ncol];
            int cfila=1;
            
            do
            {

          

            for(int i=0;i<ncol;i++)
            {
                fila[i]=data.rs.getObject(i+1);
               

            }

            modelo.addRow(fila);

          

                cfila=0;
           }while(data.rs.next());
     
    }
         catch(SQLException excepcionSql)
        {
           // System.out.println("ERROR EN LA BASE DE DATOS");
            //JOptionPane.showMessageDialog(this,"ERROR EN LA BASE DE DATOS");
        }

          this.setModel(modelo);
          


         // this.setDefaultRenderer(null, forma);
   

    }

     public DataSource getData() {
        return data;
    }

    /**
     * @param data the data to set
     */
    public void setData(DataSource data) {
        this.data = data;
        if(data!=null){
            this.conectar();

        }
    }
    
    
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
Component c = super.prepareRenderer(renderer, row, col);

if (row % 2 == 0 && !isCellSelected(row, col)) {
        c.setBackground(getColor());
} 
else {
if (isCellSelected(row, col)) {
if (this.isEnabled()) {
c.setBackground(getSelectionBackground());
} else {
// Si la tabla no esta habilitada, el color del seleccionado es diferente
c.setBackground(new Color(0xC0C0C0));
}
} else {
c.setBackground(getBackground());
}
}
return c;
}

    /**
     * @return the color
     */
    public Color getColor() {
        return color;
    }

    /**
     * @param color the color to set
     */
    public void setColor(Color color) {
        this.color = color;
    }

   

}
